package edu.wuster.blog.filter;

/*
 * 过滤器*/

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import edu.wuster.blog.entity.Result;
import edu.wuster.blog.utils.JWTUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.IOException;


@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求的url
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        String url = req.getRequestURL().toString();
        log.info("拦截到请求路径：{}", url);

        //添加这行代码，让OPTIONS请求通过
        if (req.getMethod().equals("OPTIONS")) {
            rep.setStatus(HttpServletResponse.SC_OK);
            log.info("yes");
            chain.doFilter(request,response);
            return;
        }

        //检查是否是注册请求
        if (url.contains("/register")) {
            log.info("注册请求放行");
            chain.doFilter(request, response);
            return;
        }

        //检查是否是登录请求
        if (url.contains("/login")) {
            log.info("登录请求放行");
            chain.doFilter(request, response);
            return;
        }

        //获取jwt令牌
        String jwt = req.getHeader("token");
        log.info(jwt);
        //判断jwt是否存在
        if (!StringUtils.hasLength(jwt)) {
            log.info("未登录的请求");
            //返回json格式的结果
            String notLogin = JSONObject.toJSONString(Result.error("NOT_LOGIN"), SerializerFeature.WriteMapNullValue);
            rep.getWriter().write(notLogin); //返回
            return;
        }
        //解析jwt令牌
        try {
            JWTUtils.parseJWT(jwt);
        } catch (Exception e) {
            log.info("jwt令牌解析失败");
            String notLogin = JSONObject.toJSONString(Result.error("NOT_LOGIN"), SerializerFeature.WriteMapNullValue);
            rep.getWriter().write(notLogin); //返回
            return;
        }
        //解析成功放行
        log.info("jwt令牌解析成功,放行");
        chain.doFilter(request, response);
    }
}
